/****************************************************************
 * <strong>MFEncodingFilter管理类</strong>
 *
 * <p>
 * MFEncodingFilter管理类
 * </p>
 *
 * @author AndyZhang 2011
 * @version 0.1
 * ToDo:
 ***************************************************************/

package com.thinkwide.data.filter;

import com.thinkwide.data.debug.MFDebug;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class MFEncodingFilter implements Filter { // 编码过滤器

    // 指定编码名称
    protected String encodingName;
    // 是否启用编码
    protected boolean enable;
    // 定义FilterConfig过滤配置
    protected FilterConfig filterConfig;

    public MFEncodingFilter() {
        this.encodingName = "utf-8";
        this.enable = false;
    }

    public void loadConfigParameter() {
        this.encodingName = this.filterConfig.getInitParameter("encoding");
        final String strEnable = this.filterConfig.getInitParameter("enable");
        this.enable = "true".equals(strEnable);
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        if (this.enable) {
            request.setCharacterEncoding(this.encodingName);
            response.setContentType("text/html;charset=" + this.encodingName);
        }

        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {
        MFDebug.println("启动后台Encoding过滤器服务...");
        this.filterConfig = config;
        loadConfigParameter();

    }

    public void destroy() {

    }

}

